<template>
  <view class="storeSetupPage">
    <nav-bar title="门店设置" bgColor="#ffb72f" titleColor="#fff" />

    <view class="content">
      <view class="calssTitle">门店信息</view>
      <u--form
        labelPosition="left"
        :model="formData"
        :rules="rules"
        ref="form1"
      >
        <u-form-item
          label="门店logo"
          prop="fileList"
          ref="item1"
          :labelWidth="80"
        >
          <u-upload
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="1"
          ></u-upload>
        </u-form-item>
        <u-form-item
          label="门店简称"
          prop="storeName"
          ref="item1"
          :labelWidth="80"
        >
          <view class="calcuBox">
            <view class="calcuInput">
              <u--input
                placeholder="请输入内容"
                :customStyle="{
                  border: 'none',
                  height: '54rpx',
                  padding: '13rpx 22rpx',
                  fontSize: '30rpx',
                }"
                border="surround"
                v-model="formData.storeName"
                :maxlength="20"
              ></u--input>
            </view>
            <view class="maxNum"
              >{{ formData.storeName.length || 20 }} / 20</view
            >
          </view>
        </u-form-item>
        <u-form-item
          label="门店地址"
          prop="provinceCode"
          ref="item1"
          :labelWidth="80"
        >
          <view class="areaBox" @click="openAreaPicker">
            <view v-if="formData.provinceCode" class="areaTxt"
              >{{ formData.provinceCode }}/{{ formData.cityCode }}/{{
                formData.areaCode
              }}</view
            >
            <view v-else>省/市/区</view>
            <view class="iconfont icon-xuanzeqizhankai"></view>
          </view>
          <area-picker
            ref="areaPicker"
            @getAreaPicker="getAreaPicker"
          ></area-picker>
        </u-form-item>
        <u-form-item
          label=" "
          prop="addressDetail"
          ref="item1"
          :labelWidth="80"
        >
          <view>
            <u--textarea
              v-model="formData.addressDetail"
              placeholder="请输入门店详情"
            ></u--textarea>
          </view>
        </u-form-item>
        <u-form-item label=" " prop="location" ref="item1" :labelWidth="80"
          ><view @click="getLocation" class="getLocation"
            >定位</view
          ></u-form-item
        >
        <u-form-item
          label="客服电话"
          prop="kfPhone"
          ref="item1"
          :labelWidth="80"
        >
          <u--input
            :customStyle="{
              height: '54rpx',
              padding: '13rpx 22rpx',
              fontSize: '30rpx',
            }"
            placeholder="请输入内容"
            border="surround"
            v-model="formData.kfPhone"
          ></u--input>
        </u-form-item>

        <view class="calssTitle">门店设置</view>
        <u-form-item label="营业时间" prop="time" ref="item1" :labelWidth="80">
          <view class="timeBox">
            <view @click="openSelectTimePicker" class="time">
              <view class="iconfont icon-shijian" style="color: #e4e7ed"></view>
              <view
                >{{ formData.busTime.openHour }}:{{
                  formData.busTime.openMin
                }}</view
              >
              <view>-</view>
              <view
                >{{
                  formData.busTime.openHour > formData.busTime.closeHour
                    ? "次日"
                    : ""
                }}{{ formData.busTime.closeHour }}:{{
                  formData.busTime.closeMin
                }}</view
              >
            </view>
            <view class="switchBox">
              <u-switch v-model="formData.busTimeBoolean" size="20"></u-switch>
              <view style="margin-left: 8rpx">不营业</view>
            </view>
          </view>
          <select-time-picker
            ref="selectTimePicker"
            @getTime="getTime"
            :preTime="formData.busTime"
          ></select-time-picker>
        </u-form-item>

        <block v-if="formData.industry < 100">
          <u-form-item
            label="就餐方式"
            prop="industryMode"
            ref="item1"
            :labelWidth="80"
          >
            <u-checkbox-group
              v-model="formData.caterList"
              iconPlacement="left"
              placement="row"
            >
              <u-checkbox
                :customStyle="{ marginRight: '8px' }"
                v-for="(item, index) in formData.caterOption"
                :key="index"
                :label="item.name"
                :name="item.name"
              ></u-checkbox>
            </u-checkbox-group>
          </u-form-item>
          <u-form-item v-if="formData.caterList.includes('打包')">
            <view
              style="margin-left: 180rpx; display: flex; align-items: center"
            >
              <view style="float: left">打包费</view>
              <view style="width: 200rpx; margin: 0 16rpx"
                ><u--input
                  border="surround"
                  v-model="formData.caterPackFee"
                ></u--input
              ></view>
              <view style="float: left">元</view>
            </view>
          </u-form-item>
          <u-form-item v-if="formData.caterList.includes('同城配送')">
            <view
              style="margin-left: 180rpx; display: flex; align-items: center"
            >
              <view style="float: left">配送费</view>
              <view style="width: 200rpx; margin: 0 16rpx"
                ><u--input
                  border="surround"
                  v-model="formData.caterPatchFee"
                ></u--input
              ></view>
              <view style="float: left">元</view>
            </view>
          </u-form-item>
        </block>
        <block v-else>
          <u-form-item
            label="配送方式"
            prop="industryMode"
            ref="item1"
            :labelWidth="80"
          >
            <u-checkbox-group
              v-model="formData.dispatchList"
              iconPlacement="left"
              placement="row"
            >
              <u-checkbox
                :customStyle="{ marginRight: '8px' }"
                v-for="(item, index) in formData.dispatchOption"
                :key="index"
                :label="item.name"
                :name="item.name"
              ></u-checkbox>
            </u-checkbox-group>
          </u-form-item>
          <u-form-item v-if="formData.dispatchList.includes('自提')">
            <view
              style="margin-left: 180rpx; display: flex; align-items: center"
            >
              <view style="float: left">包装费</view>
              <view style="width: 200rpx; margin: 0 16rpx"
                ><u--input
                  border="surround"
                  v-model="formData.disPackFee"
                ></u--input
              ></view>
              <view style="float: left">元</view>
            </view>
          </u-form-item>
          <u-form-item v-if="formData.dispatchList.includes('同城配送')">
            <view
              style="margin-left: 180rpx; display: flex; align-items: center"
            >
              <view style="float: left">配送费</view>
              <view style="width: 200rpx; margin: 0 16rpx"
                ><u--input
                  border="surround"
                  v-model="formData.disPatchFee"
                ></u--input
              ></view>
              <view style="float: left">元</view>
            </view>
          </u-form-item>
        </block>

        <u-form-item label="店铺描述" prop="" ref="item1" :labelWidth="80"
          ><u--textarea
            v-model="formData.storeDes"
            count
            maxlength="200"
          ></u--textarea
        ></u-form-item>
        <u-form-item label="店铺分享文案" prop="" ref="item1" :labelWidth="80">
          <u--textarea
            v-model="formData.storeShareTxt"
            count
            maxlength="40"
          ></u--textarea>
        </u-form-item>
      </u--form>
    </view>
    <view class="submit">
      <u-button
        @click="cancel"
        :customStyle="{ width: '250rpx' }"
        type="primary"
        :plain="true"
        text="取消"
      ></u-button>
      <u-button
        @click="submit"
        :customStyle="{ width: '250rpx' }"
        type="primary"
        text="保存"
      ></u-button>
    </view>
  </view>
</template>

<script>
import selectTimePicker from "@/components/pageComponents/sp-store/select-time-picker/index.vue";
import areaPicker from "@/components/pageComponents/sp-store/area-picker/index.vue";
import {
  uploadAvater,
  getShopDetail,
  saveShopDetail,
} from "@/service/api/sp-store/index.js";
import { getToken } from "@/utils/auth";
export default {
  components: {
    selectTimePicker,
    areaPicker,
  },
  data() {
    return {
      // 规则校验
      rules: {
        fileList: {
          asyncValidator: (rule, value, callback) => {
            if (this.fileList1.length < 1) {
              callback(new Error("请上传logo"));
            } else {
              callback();
            }
          },
        },
        storeName: {
          type: "string",
          required: true,
          message: "请输入门店简称",
          trigger: ["blur", "change"],
        },
        provinceCode: {
          type: "string",
          required: true,
          message: "请输入门店地址",
          trigger: ["blur", "change"],
        },
        addressDetail: {
          type: "string",
          required: true,
          message: "请输入门店地址",
          trigger: ["blur", "change"],
        },
        location: {
          asyncValidator: (rule, value, callback) => {
            if (!this.formData.longitude) {
              callback(new Error("请定位门店地址"));
            } else {
              callback();
            }
          },
        },
        kfPhone: [
          {
            required: true,
            message: "请输入客服电话",
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            trigger: ["change", "blur"],
          },
        ],
        time: {
          asyncValidator: (rule, value, callback) => {
            let { openHour, openMin, closeHour, closeMin } =
              this.formData.busTime;
            if (
              openHour === "00" &&
              openMin === "00" &&
              closeHour === "00" &&
              closeMin === "00"
            ) {
              callback(new Error("请设置营业时间"));
            } else {
              callback();
            }
          },
        },
        industryMode: {
          asyncValidator: (rule, value, callback) => {
            if (
              this.formData.industry < 100 &&
              this.formData.caterList.length < 1
            ) {
              callback(new Error("请选择就餐方式"));
            } else if (
              this.formData.industry >= 100 &&
              this.formData.dispatchList.length < 1
            ) {
              callback(new Error("请选择配送方式"));
            } else {
              callback();
            }
          },
        },
      },
      fileList1: [],
      formData: {
        /* 门店信息 */
        id: "",
        industry: "", // < 100 时就餐方式，否则配送方式
        storeName: "",
        kfPhone: "",
        // 地址
        provinceCode: "",
        cityCode: "",
        areaCode: "",
        addressDetail: "",
        longitude: "",
        latitude: "",
        /* 门店设置 */
        busTime: {
          openHour: "00",
          openMin: "00",
          closeHour: "00",
          closeMin: "00",
        },
        busTimeBoolean: false,
        // 就餐方式
        caterList: [],
        caterOption: [
          {
            name: "堂食",
            disabled: false,
          },
          {
            name: "打包",
            disabled: false,
          },
          {
            name: "同城配送",
            disabled: false,
          },
        ],
        caterPackFee: "",
        caterPatchFee: "",
        // 配送方式
        dispatchList: [],
        dispatchOption: [
          {
            name: "到店消费",
            disabled: false,
          },
          {
            name: "自提",
            disabled: false,
          },
          {
            name: "同城配送",
            disabled: false,
          },
        ],
        disPackFee: "",
        disPatchFee: "",
        // 店铺描述
        storeDes: "",
        // 店铺分享文案
        storeShareTxt: "",
      },
    };
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.form1.setRules(this.rules);
  },
  mounted() {
    this.shopDetailFun();
  },
  methods: {
    // 上传图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      let params = {
        file: url,
      };
      // uploadAvater(params).then(res => {
      // 	console.log('上传')
      // })
      let headers = { "X-BUSINESS-TOKEN": getToken() };
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: `${process.env.VUE_APP_BASE_URL}/business_admin/upload`, // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {},
          header: headers,
          success: (res) => {
            setTimeout(() => {
              let { baseUrl, path } = JSON.parse(res.data).data;
              let imgUrl = baseUrl + path;
              resolve(imgUrl);
            }, 1000);
          },
        });
      });
    },

    // 省市区
    openAreaPicker() {
      this.$refs.areaPicker.open();
    },
    getAreaPicker(val) {
      console.log("接收省市区", val);
      this.formData.provinceCode = val.value[0];
      this.formData.cityCode = val.value[1];
      this.formData.areaCode = val.value[2];
    },
    getLocation() {
      let that = this;
      uni.chooseLocation({
        longitude: that.formData.longitude,
        latitude: that.formData.latitude,
        success: function (res) {
          console.log("位置名称：" + res.name);
          console.log("详细地址：" + res.address);
          console.log("纬度：" + res.latitude);
          console.log("经度：" + res.longitude);
          if (res.address) {
            that.formData.addressDetail = res.address;
            that.formData.longitude = res.longitude;
            that.formData.latitude = res.latitude;
          }
        },
      });
    },
    // 营业时间
    openSelectTimePicker() {
      this.$refs.selectTimePicker.open();
    },
    getTime(e) {
      console.log("营业时间", e);
      this.formData.busTime = e;
    },

    // 提交
    cancel() {
      this.$Router.back();
    },
    submit() {
      this.$refs.form1
        .validate()
        .then((res) => {
          this.saveShopFun();
        })
        .catch((errors) => {
          uni.$u.toast("信息不全，请补充");
        });
    },
    saveShopFun() {
      let that = this;
      // 格式化
      let params = Object.assign({}, this.formData);
      let data = {
        id: params.id,
        logo: this.fileList1[0].url.replace(
          "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/",
          ""
        ),
        shopName: params.storeName,
        phone: params.kfPhone,
        // 地址
        provinceCode: params.provinceCode,
        cityCode: params.cityCode,
        areaCode: params.areaCode,
        address: params.addressDetail,
        longitude: params.longitude,
        latitude: params.latitude,
        // 营业时间
        openHour: params.busTime.openHour,
        openMin: params.busTime.openMin,
        closeHour: params.busTime.closeHour,
        closeMin: params.busTime.closeMin,
        isTrade: params.busTimeBoolean === false ? 0 : 1,
        // 就餐方式
        diningConfigJson: {
          isEatShop: params.caterList.includes("堂食") ? true : false,
          isDelivery: params.caterList.includes("同城配送") ? true : false,
          deliveryFee: params.caterPatchFee * 100,
          isPack: params.caterList.includes("打包") ? true : false,
          packFee: params.caterPackFee * 100,
        },
        // 配送方式
        deliveryServiceConfigJson: {
          isShopConsume: params.dispatchList.includes("到店消费")
            ? true
            : false,
          isSelfPack: params.dispatchList.includes("自提") ? true : false,
          packFee: params.disPackFee * 100,
          isDelivery: params.dispatchList.includes("同城配送") ? true : false,
          deliveryFee: params.disPatchFee * 100,
        },
        desc: params.storeDes,
        copywrite: params.storeShareTxt,
      };
      saveShopDetail(data).then((res) => {
        wx.showToast({
          title: "修改成功",
          duration: 2000,
          icon: "success",
          success: function () {
            setTimeout(() => {
              that.$Router.back();
            }, 2000);
          },
        });
      });
    },

    // 详情
    shopDetailFun() {
      console.log(this.$Route.query);
      const { id } = this.$Route.query;
      getShopDetail({ pubShopId: id }).then((res) => {
        console.log("门店详情", res);

        // 格式化
        // 门店信息
        this.fileList1.push({
          url: `https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/${res.logo}`,
        });
        let params = Object.assign({}, this.formData);
        params.id = res.id;
        params.industry = res.industry;
        params.storeName = res.shopName;
        params.kfPhone = res.phone;
        // 地址
        params.provinceCode = res.provinceCode;
        params.cityCode = res.cityCode;
        params.areaCode = res.areaCode;
        params.addressDetail = res.address;
        params.longitude = res.longitude;
        params.latitude = res.latitude;
        // 营业时间
        let busTime = {
          openHour:
            String(res.openHour).length < 2 ? "0" + res.openHour : res.openHour,
          openMin:
            String(res.openMin).length < 2 ? "0" + res.openMin : res.openMin,
          closeHour:
            String(res.closeHour).length < 2
              ? "0" + res.closeHour
              : res.closeHour,
          closeMin:
            String(res.closeMin).length < 2 ? "0" + res.closeMin : res.closeMin,
        };
        params.busTime = busTime;
        params.busTimeBoolean = res.isTrade === 0 ? false : true;
        // 就餐方式
        let { isEatShop, isPack, packFee, isDelivery, deliveryFee } =
          res.diningConfigJson;
        if (isEatShop) {
          params.caterList.push("堂食");
        }
        if (isPack) {
          params.caterList.push("打包");
          params.caterPackFee = packFee / 100;
        }
        if (isDelivery) {
          params.caterList.push("同城配送");
          params.caterPatchFee = deliveryFee / 100;
        }
        // 配送方式
        let {
          isShopConsume,
          isSelfPack,
          packFee: disPackFee,
          isDelivery: is_Delivery,
          deliveryFee: disPatchFee,
        } = res.deliveryServiceConfigJson;
        if (isShopConsume) {
          params.dispatchList.push("到店消费");
        }
        if (isSelfPack) {
          params.dispatchList.push("自提");
          params.disPackFee = disPackFee / 100;
        }
        if (is_Delivery) {
          params.dispatchList.push("同城配送");
          params.disPatchFee = deliveryFee / 100;
        }
        // 店铺描述
        params.storeDes = res.desc;
        // 店铺分享文案
        params.storeShareTxt = res.copywrite;
        this.formData = params;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.storeSetupPage {
  padding: 20rpx;
  box-sizing: border-box;
  .calssTitle {
    font-weight: bold;
    font-size: 36rpx;
  }
  .content {
    .calcuBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      text-align: center;
      border: 1rpx solid #e5e7ed;
      border-radius: 8rpx;
      color: #c0c4cc;
      .calcuInput {
        flex: 3;
      }
      .maxNum {
        flex: 1;
      }
    }
    .areaBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border: 1rpx solid #e5e7ed;
      border-radius: 8rpx;
      height: 54rpx;
      padding: 13rpx 22rpx;
      font-size: 30rpx;
      color: #c0c4cc;
      .areaTxt {
        color: #000000;
      }
    }
    .getLocation {
      color: $u-primary;
    }
    .timeBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24rpx;
      .time {
        flex: 1;
        display: flex;
        justify-content: space-around;
        align-items: center;
        border: 1rpx solid #e4e7ed;
        border-radius: 8rpx;
        padding: 12rpx 18rpx;
        box-sizing: border-box;
      }
      .switchBox {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
    }
  }
  .submit {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
}
</style>
